<template>
  <div>
    <div class="card mb-3 r-form">
      <div class="card-body">
        <div class="font-weight-bold mb-3">续贷{{ isEdit ? '申请' : '信息' }}：</div>
        <div class="d-flex mb-2">
          <label class="col-form-label r-form-label">{{ isEdit ? '预计' : '' }}续贷金额</label>
          <div class="flex-1 mb-2">
            <el-input
              v-model="formData.new_apply_funds"
              v-input-number="{ min: 0, fixed: 2 }"
              type="number"
              :disabled="isView"
            >
              <template slot="append">万元</template>
            </el-input>
          </div>
          <label class="col-form-label r-form-label">{{ isEdit ? '预计' : '' }}续贷年限</label>
          <div class="flex-1">
            <el-input
              v-model="formData.new_load_years"
              v-input-number="{ min: 0, fixed: 0 }"
              type="number"
              @input="calcLoadEndDate"
              :disabled="isView"
            >
              <template slot="append">月</template>
            </el-input>
          </div>
        </div>
        <div class="d-flex mb-2">
          <label class="col-form-label r-form-label">贷款时间</label>
          <div class="flex-1 mb-2">
            <el-date-picker
              v-model="formData.new_load_date"
              class="w-100"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              :picker-options="pickerOptions"
              :default-value="defaultDate"
              :disabled="isView"
              @change="calcLoadEndDate"
            ></el-date-picker>
          </div>
          <label class="col-form-label r-form-label">到期时间</label>
          <div class="flex-1 mb-2">
            <el-date-picker
              v-model="formData.new_load_end_date"
              class="w-100"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              :picker-options="pickerOptions"
              :default-value="defaultDate"
              :disabled="true"
            ></el-date-picker>
          </div>
        </div>
        <div class="d-flex mb-2">
          <label class="col-form-label r-form-label">贷款利率</label>
          <div class="flex-1 mb-2">
            <el-input
              v-model="formData.new_load_rate"
              v-input-number="{ min: 0, fixed: 2 }"
              type="number"
              :disabled="isView"
            >
              <template slot="append">%</template>
            </el-input>
          </div>
          <label class="col-form-label r-form-label">担保费率</label>
          <div class="flex-1">
            <el-input
              v-model="formData.new_gua_rate"
              v-input-number="{ min: 0, fixed: 2 }"
              type="number"
              :disabled="isView"
            >
              <template slot="append">%</template>
            </el-input>
          </div>
        </div>
        <div class="d-flex mb-2">
          <div class="flex-1 d-flex">
            <template v-if="isComplete">
              <label class="col-form-label r-form-label">续贷附件</label>
              <div class="flex-1">
                <upload-oss
                  multiple
                  listType="picture-card"
                  ref="uploadFinish"
                  accept="image/*"
                  :on-complete="handleCompleteFinish"
                  :file-list="finishFileList"
                  class="form-control-ml"
                ></upload-oss>
              </div>
            </template>
            <template v-else>
              <label class="col-form-label r-form-label">附件上传</label>
              <div class="flex-1">
                <img-card :images="attachList" v-if="isView"></img-card>
                <upload-oss
                  v-else
                  multiple
                  listType="picture-card"
                  ref="upload"
                  accept="image/*"
                  :on-complete="handleComplete"
                  :file-list="fileList"
                  class="form-control-ml"
                ></upload-oss>
              </div>
            </template>
          </div>
          <div class="flex-1">
            <div class="d-flex" v-if="viewMode !== 2">
              <label class="col-form-label r-form-label">情况说明</label>
              <div class="flex-1">
                <el-input type="textarea" v-model="formData.des" :disabled="isView"></el-input>
              </div>
            </div>
            <div class="ml-5" v-if="viewMode > 1">
              <table class="table table-borderless table-sm vertical-align-middle">
                <tbody>
                  <tr>
                    <td>1、档案卡填写</td>
                    <td>
                      <span class="text-muted">当前状态：</span>
                      <span :class="`text-${creditCardStatus.color}`">
                        {{ creditCardStatus.label }}
                      </span>
                    </td>
                    <td>
                      <el-button
                        v-if="(isView && projectStatus === 1) || isComplete"
                        type="text"
                        :icon="isView ? 'el-icon-search' : 'el-icon-edit'"
                        @click="handleCreditEdit"
                      ></el-button>
                    </td>
                  </tr>
                  <tr>
                    <td>2、合同处理</td>
                    <td>
                      <span class="text-muted">当前状态：</span>
                      <span :class="`text-${contractStatusObj.color}`">
                        {{ contractStatusObj.label }}
                      </span>
                    </td>
                    <td>
                      <el-button
                        v-if="(isView && contractStatus === 1) || isComplete"
                        type="text"
                        :icon="isView ? 'el-icon-search' : 'el-icon-edit'"
                        @click="handleContractEdit"
                      ></el-button>
                    </td>
                  </tr>
                  <tr>
                    <td>3、放款通知书</td>
                    <td>
                      <span class="text-muted">当前状态：</span>
                      <span :class="`text-${noticeStatusObj.color}`">
                        {{ noticeStatusObj.label }}
                      </span>
                    </td>
                    <td>
                      <el-button
                        v-if="(isView && noticeStatus === 1) || isComplete"
                        type="text"
                        :icon="isView ? 'el-icon-search' : 'el-icon-edit'"
                        @click="handleNoticeEdit"
                      ></el-button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mb-3 text-center" v-if="viewMode === 1">
      <el-button type="primary" class="btn-long" :loading="loading" @click="agreeRenewal">
        同意续贷
      </el-button>
      <el-button class="btn-long" :disabled="loading" @click="rejectRenewal">拒绝</el-button>
    </div>

    <div class="mb-3 text-center" v-if="isComplete">
      <el-button type="primary" class="btn-long" :loading="loading" @click="agreeFinish">
        完成
      </el-button>
      <el-button class="btn-long" :disabled="loading" @click="rejectFinish">拒绝</el-button>
    </div>

    <div class="mb-3 text-center" v-else-if="viewMode === 0">
      <el-button type="primary" class="btn-long" :loading="loading" @click="submit">完成</el-button>
      <el-button class="btn-long" :disabled="loading" @click="dismiss">取消</el-button>
    </div>

    <div class="card mb-3" v-if="viewMode === 3 && +renewalData.approval_status === 3">
      <div class="card-body">
        <div class="font-weight-bold mb-3">拒绝信息：</div>
        <div class="d-flex mb-2">
          <div class="flex-1">
            <div class="d-flex mb-2">
              <label class="col-form-label r-form-label">拒绝时间</label>
              <div class="flex-1 input-static">{{ renewalData.confuse_time }}</div>
            </div>
            <div class="d-flex">
              <label class="col-form-label r-form-label">操作人</label>
              <div class="flex-1 input-static">{{ renewalData.confuse_person }}</div>
            </div>
          </div>
          <div class="flex-1 d-flex">
            <label class="col-form-label r-form-label">拒绝理由</label>
            <div class="flex-1 input-static">{{ renewalData.confuse_reason }}</div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :visible.sync="creditVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="1000px"
    >
      <renewal-credit
        :query-id="creditId"
        :view-mode="isView"
        @success="handleCreditSuccess"
      ></renewal-credit>
    </el-dialog>

    <el-dialog
      :visible.sync="noticeVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="1000px"
    >
      <register-loan-notice
        :related-data="formData"
        :view-mode="isView"
        @success="handleNoticeSuccess"
      ></register-loan-notice>
    </el-dialog>

    <renewal-contract-dialog
      :visible.sync="contractVisible"
      :renewal-data="complexRenewalData"
      :view-mode="isView"
      @success="handleContractSuccess"
    ></renewal-contract-dialog>

    <renewal-notice-dialog
      :visible.sync="noticeVisible"
      :renewal-data="complexRenewalData"
      :view-mode="isView"
      @success="handleNoticeSuccess"
    ></renewal-notice-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { dateFromString, arrayFromString } from '@vimi/utils-tool'
import { strFromOss } from '@/common/plugins/tools/format'

import ImgCard from '@/components/ImgCard'
import RegisterLoanNotice from '@/credit/views/county/mission/RegisterLoanNotice'
import RenewalCredit from '@/credit/components/creditFile/RenewalCredit'
import RenewalContractDialog from '@/credit/views/city/risk/RenewalContractDialog'
import RenewalNoticeDialog from '@/credit/views/city/risk/RenewalNoticeDialog'

export default {
  components: {
    ImgCard,
    RegisterLoanNotice,
    RenewalCredit,
    RenewalContractDialog,
    RenewalNoticeDialog,
  },
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    renewalData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      loading: false,
      tableName: 'credit_extended_loan',
      formData: {
        new_apply_funds: '',
        new_load_years: '',
        new_load_date: '',
        new_load_end_date: '',
        new_load_rate: '',
        new_gua_rate: '',
        des: '',
        attachment: '',
      },
      attachList: [],
      fileList: [],
      finishFileList: [],

      projectStatus: 0,
      creditVisible: false,
      creditId: '',

      contractStatus: 0,
      contractVisible: false,

      noticeStatus: 0,
      noticeVisible: false,
    }
  },
  computed: {
    ...mapGetters(['user']),
    loadEndDate() {
      return dateFromString(this.relatedData.load_end_date) || Date.now()
    },
    pickerOptions() {
      return {
        disabledDate: time => time <= this.loadEndDate,
      }
    },
    defaultDate() {
      return this.loadEndDate
    },
    renewalId() {
      return this.renewalData.credit_extended_loan_id
    },
    isAddEdit() {
      return !this.renewalId
    },
    isEdit() {
      return this.viewMode === 0
    },
    isApproval() {
      return this.viewMode === 1
    },
    isComplete() {
      return this.viewMode === 2
    },
    isView() {
      return this.viewMode === 3
    },
    creditCardStatus() {
      return this.projectStatus === 0
        ? { label: '未处理', color: 'danger' }
        : { label: '已处理', color: 'success' }
    },
    contractStatusObj() {
      return this.contractStatus === 0
        ? { label: '未处理', color: 'danger' }
        : { label: '已处理', color: 'success' }
    },
    noticeStatusObj() {
      return this.noticeStatus === 0
        ? { label: '未处理', color: 'danger' }
        : { label: '已处理', color: 'success' }
    },
    complexRenewalData() {
      return {
        ...this.renewalData,
        bank_id: this.relatedData.bank_id,
        bank_name: this.relatedData.bank_name,
        ele_letter_status: 2,
      }
    },
    approvalStatus() {
      return +this.relatedData.approval_status
    },
  },
  watch: {
    relatedData: {
      handler: function (val) {
        this.initRelatedData(val)
      },
      deep: true,
      immediate: true,
    },
    renewalData: {
      handler: function (val) {
        this.init(val)
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    init(val) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = val[key] || ''
      })
      this.projectStatus = +(val.project_status || 0)
      this.noticeStatus = +(val.notice_status || 0)
      this.contractStatus = +(val.contract_status || 0)
      this.attachList = arrayFromString(val.attachment)
      this.fileList = this.attachList.map(item => ({ url: item }))
    },
    initRelatedData() {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = this.renewalData[key] || ''
      })
    },
    calcLoadEndDate() {
      const { new_load_date: startDate, new_load_years: loadYears } = this.formData
      if (!startDate || !loadYears) return
      const date = new Date(startDate)

      const year = date.getFullYear()
      const month = date.getMonth() + 1 + Number.parseInt(loadYears)
      const day = Math.min(date.getDate(), new Date(year, month, 0).getDate())

      this.formData.new_load_end_date = `${year}-${this.panStart(month)}-${this.panStart(day)}`
    },
    panStart(str) {
      return `${str || ''}`.padStart(2, '0')
    },
    dismiss() {
      this.$emit('dissmiss', true)
    },
    submit() {
      this.validate()
        .then(() => {
          this.loading = true
          this.$refs.upload.submit()
        })
        .catch(err => {
          this.$message.error((err && err.message) || '输入错误，请重新输入')
        })
    },
    validate() {
      const validateObj = {
        new_apply_funds: '请填写续贷金额',
        new_load_years: '请填写续贷年限',
        new_load_date: '请选择贷款时间',
        new_load_end_date: '请选择到期时间',
        new_load_rate: '请填写贷款利率',
        new_gua_rate: '请填写担保费率',
        des: '请填写情况说明',
      }
      return new Promise((resolve, reject) => {
        if (this.isAddEdit && (!this.relatedData || !this.relatedData.customer_related_id)) {
          return reject(new Error('请选择贷后项目'))
        }

        for (const key in validateObj) {
          if (!this.formData[key]) {
            return reject(new Error(validateObj[key]))
          }
        }

        resolve()
      })
    },
    handleComplete(images) {
      this.formData.attachment = strFromOss(images)
      const id = this.renewalData.credit_extended_loan_id
      if (id) {
        this.updateData(id, this.formData, '修改')
      } else {
        const data = {
          ...this.formData,
          ...this.copyFromRelated(),
          extended_loan_type: 2,
        }
        this.addData(data)
      }
    },
    copyFromRelated() {
      const { relatedData } = this
      return [
        'address',
        'address_code',
        'customer_name',
        'customer_related_id',
        'left_funds',
        'load_end_date',
        'mobile_no',
        'res_person',
        'corp_name',
        'service_id',
        'res_a',
        'res_b',
        'borrowing_reason',
        'business_des',
        'business_scope',
        'bussiness_years',
        'counter_guarantee',
        'credit_type_list',
        'emp_temp_total',
        'finance_des',
        'invest_report_result',
        'poverty_households',
        'project_des',
        'year_emp_exp',
      ].reduce((prev, key) => {
        prev[key] = relatedData[key]
        return prev
      }, {})
    },
    async addData(data) {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.addData(this.$serviceName, this.tableName, data)
      )
      this.loading = false
      if (!res) return this.$message.error('登记失败，请重试')
      this.$message.success('登记成功')
      this.$emit('success', res)
    },
    async updateData(id, data, label) {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(this.$serviceName, this.tableName, id, data)
      )
      this.loading = false
      if (label) {
        if (!res) return this.$message.error(`${label}失败，请重试`)
        this.$message.success(`${label}成功`)
        this.$emit('success', res)
      }
    },
    agreeRenewal() {
      this.$utils.msgbox({
        message: '确定同意续贷?',
        beforeClose: () =>
          this.updateData(
            this.renewalData.credit_extended_loan_id,
            {
              ...this.formData,
              approval_status: 1,
            },
            '同意续贷'
          ),
      })
    },
    rejectRenewal() {
      this.$prompt('拒绝理由：', '续贷拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入拒绝理由',
        inputType: 'textarea',
        inputValidator: value => (!value ? '请输入拒绝理由' : true),
      }).then(({ value }) => {
        this.updateData(
          this.renewalData.credit_extended_loan_id,
          {
            confuse_person: this.user.realName,
            confuse_time: this.$utils.dateFormat(new Date()),
            confuse_reason: value,
            approval_status: 3,
          },
          '拒绝'
        )
      })
    },
    validateFiles() {
      return new Promise((resolve, reject) => {
        if (this.projectStatus === 0) {
          return reject(new Error('请先完成档案卡'))
        }
        if (this.contractStatus === 0) {
          return reject(new Error('请先完成合同处理'))
        }
        if (this.noticeStatus === 0) {
          return reject(new Error('请先完成放款通知书'))
        }
        resolve()
      })
    },
    agreeFinish() {
      this.validate()
        .then(() => {
          // return this.validateFiles()
        })
        .then(() => {
          this.loading = true
          this.$refs.uploadFinish.submit()
        })
        .catch(err => {
          this.$message.error((err && err.message) || '输入错误，请重新输入')
        })
    },
    handleCompleteFinish(images) {
      const attachment = strFromOss([...this.fileList, ...images])
      const id = this.renewalData.credit_extended_loan_id
      this.updateData(
        id,
        {
          ...this.formData,
          attachment,
          approval_status: 2,
          extended_loan_type: 2,
        },
        '完成续贷'
      )
    },
    rejectFinish() {
      this.$prompt('拒绝理由：', '续贷拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入拒绝理由',
        inputType: 'textarea',
        inputValidator: value => (!value ? '请输入拒绝理由' : true),
      }).then(({ value }) => {
        this.updateData(
          this.renewalData.credit_extended_loan_id,
          {
            confuse_person: this.user.realName,
            confuse_time: this.$utils.dateFormat(new Date()),
            confuse_reason: value,
            approval_status: 3,
          },
          '拒绝'
        )
      })
    },

    // 档案卡
    handleCreditEdit() {
      this.creditId = this.renewalId
      this.creditVisible = true
    },
    handleCreditSuccess() {
      this.creditVisible = false
      this.$emit('success', { close: false })
      this.projectStatus = 1
    },

    // 合同处理
    handleContractEdit() {
      this.$store.dispatch('getEntrustContract', this.renewalId)
      this.contractVisible = true
    },
    handleContractSuccess() {
      if (+this.renewalData.contract_status === 0) {
        this.updateData(
          this.renewalId,
          {
            contract_status: 1,
          },
          ''
        )
      }
      this.$emit('success', { close: false })
      this.contractStatus = 1
    },

    // 放款通知书
    handleNoticeEdit() {
      this.noticeVisible = true
    },
    handleNoticeSuccess() {
      if (+this.renewalData.notice_status === 0) {
        this.updateData(
          this.renewalId,
          {
            notice_status: 1,
          },
          ''
        )
      }
      this.$emit('success', { close: false })
      this.noticeStatus = 1
    },
  },
}
</script>

<style lang="scss" scoped>
.r-form {
  /deep/ .el-input.is-disabled .el-input__inner,
  /deep/ .el-textarea.is-disabled .el-textarea__inner {
    color: $gray-600;
  }
  &-label {
    width: 110px;
    text-align: right;
    margin-right: 0.5rem;
  }
}
.input-static {
  border-radius: 4px;
  border: 1px solid $border-color;
  padding: 6px 15px;
  min-height: 36px;
  background-color: #f5f7fa;
  color: $gray-600;
  cursor: not-allowed;
}
.vertical-align-middle td {
  vertical-align: middle;
}
</style>
